//
//  Person.m
//  SSL_Runtime_Learn
//
//  Created by SSLong on 2018/2/7.
//  Copyright © 2018年 sunshilong. All rights reserved.
//

#import "Person.h"
#import <objc/runtime.h>

@implementation Person
- (void)initAperson{
    if (self.delegate && [self.delegate respondsToSelector:@selector(getBack)]) {
        [self.delegate getBack];
    }
}
#pragma mark --- 方法1
//#pragma mark --- 归档操作
//- (void)encodeWithCoder:(NSCoder *)aCoder{
//    //设置归档属性
//    [aCoder encodeObject:self.name forKey:@"name"];
//    [aCoder encodeObject:self.idcard forKey:@"idCord"];
//    [aCoder encodeInteger:self.age forKey:@"age"];
//    [aCoder encodeFloat:self.height forKey:@"height"];
//}
//#pragma mark --- 解档
//- (instancetype)initWithCoder:(NSCoder *)aDecoder{
//    self = [super init];
//    if (self) {
//        self.name = [aDecoder decodeObjectForKey:@"name"];
//        self.idcard = [aDecoder decodeObjectForKey:@"idCord"];
//        self.age = [[aDecoder decodeObjectForKey:@"age"] integerValue];
//        self.height = [[aDecoder decodeObjectForKey:@"height"] floatValue];
//    }
//    return self;
//}
#pragma mark --- 方法2，使用runtime
#pragma mark --- 归档
- (void)encodeWithCoder:(NSCoder *)aCoder{
    unsigned int count = 0;//属性个数
    Ivar *ivars = class_copyIvarList([Person class], &count);
    for (int i=0; i<count; i++) {
        //获取属性名字
        Ivar ivar = ivars[i];
        const char *name = ivar_getName(ivar);//c字符串
        NSString *key = [NSString stringWithUTF8String:name];//转为OC字符串
        //kvc,归档
        [aCoder encodeObject:[self valueForKey:key] forKey:key];
    }
    free(ivars);//c语言函数，ARC不能处理，需要手动释放
}
#pragma mark --- 解档
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super init];
    if (self) {
        //解档
        unsigned int count = 0;
        Ivar *ivars = class_copyIvarList([Person class], &count);
        
        for (int i=0; i<count; i++) {
            //取出属性
            Ivar ivar = ivars[i];
            const char *name = ivar_getName(ivar);
            NSString *key = [NSString stringWithUTF8String:name];
            
            id value = [aDecoder decodeObjectForKey:key];
            
            //kvc赋值
            [self setValue:value forKey:key];
        }
        
        free(ivars);
    }
    
    return self;
}
@end
